import express from 'express';
import xcxAddressModel from "../../../mongo/models/address"
const router = express.Router();

// 新增地址
router.post("/xcx/address/add", (req: any, res) => {
    const { openid } = req.jwtInfo
    const { name, phone, province, city, county, detail, isDefault } = req.body
    // 写入数据库 
    xcxAddressModel.create({ openid, name, phone, province, city, county, detail, isDefault, isDelete: false }).then((info) => {
        // 如果当前是默认的清除其它
        if (isDefault) {
            xcxAddressModel.updateMany({ openid, isDefault: true }, { isDefault: false })
        }
        res.send({ code: 200, msg: "添加成功" })
    }).catch((err) => {
        res.send({ code: 400, msg: "添加失败" })
    })
})

// 删除地址
router.post("/xcx/address/delete", (req: any, res) => {
    const { openid } = req.jwtInfo
    const { id } = req.body
    xcxAddressModel.updateOne({ _id: id, openid }, { isDelete: true }).then((info) => {
        res.send({ code: 200, msg: "删除成功" })
    }).catch((err) => {
        res.send({ code: 400, msg: "删除失败" })
    })
})

// 修改地址
router.post("/xcx/address/update", (req: any, res) => {
    const { openid } = req.jwtInfo
    const { id, name, phone, province, city, county, detail, isDefault } = req.body
    xcxAddressModel.updateOne({ _id: id, openid }, { name, phone, province, city, county, detail, isDefault, isDelete: false }).then((info) => {
        res.send({ code: 200, msg: "修改成功" })
    }).catch((err) => {
        res.send({ code: 400, msg: "修改失败" })
    })
})

// 获取地址列表
router.get("/xcx/address/list", (req: any, res) => {
    const { openid } = req.jwtInfo
    xcxAddressModel
        .find({ openid, isDelete: false })
        .sort({ _id: -1 })
        .exec()
        .then((info) => {
            res.send({ code: 200, msg: "获取成功", data: info })
        }).catch((err) => {
            res.send({ code: 400, msg: "获取失败" })
        })
})

export default router;
